/**
 * Copyright (c) 2015-2018, Golly Hu 胡高 (3722711@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.hg.jfsa.manage.controller.system;

import cn.hg.base.jfinal.controller.BaseController;
import cn.hg.jfsa.manage.service.JfsaOptionService;
import cn.hg.jfsa.manage.service.JfsaThemeService;
import cn.hg.jfsa.web.theme.Theme;
import cn.hg.jfsa.web.theme.ThemeException;
import cn.hg.jfsa.web.theme.ThemeManager;
import com.jfinal.aop.Inject;
import com.jfinal.kit.StrKit;
import net.sf.ehcache.CacheManager;

import java.util.List;

/**
 * @author Golly
 *
 */
public class JfsaThemeController extends BaseController {

	@Inject
	private JfsaOptionService optionService;

	@Inject
	private JfsaThemeService themeService;

	/**
	 * 打开选择主题主页面
	 */
	@Override
	public void index() {
		List<Theme> themeList = ThemeManager.me().getInstalledThemes();
		Theme currTheme = ThemeManager.me().getCurrentTheme();

		this.setAttr("themeList", themeList);
		this.setAttr("currTheme", currTheme);
	}

	/**
	 * Ajax方式修改主题
	 */
	public void ajaxChangeTheme() {
		String themeId = this.getPara("themeId");
		if (StrKit.isBlank(themeId)) {
			this.renderAjaxFailed("1", "主题不存在！");
			return;
		}

		List<Theme> themeList = ThemeManager.me().getInstalledThemes();
		Theme currTheme = ThemeManager.me().getCurrentTheme();
		if (currTheme.getId().equals(themeId)) {
			this.renderAjaxFailed("1", "此主题已经在使用中。。。");
			return;
		}
		boolean act = false;
		for (Theme theme : themeList) {
			if (theme.getId().equals(themeId)) {
				act = optionService.setOption("web_theme_id", themeId);
			}
		}

		if (act) {
			try {
				ThemeManager.me().setCurrentTheme(themeId);
				CacheManager.getInstance().removeAllCaches(); // 设置成功时清除缓存
			} catch (ThemeException e) {
				this.renderAjaxFailed("1", "主题设置失败！");
			}
			this.renderAjaxSuccessed();
		} else {
			this.renderAjaxFailed("1", "主题设置失败！");
		}
	}

}
